<?php 
/**
 *
 * UCLibFace class file
 *
 * @category   UC
 * @author     刘海涛 <liuhaitao01@snda.com>
 * @copyright  SDO Group
 * @version    Release: 1.0.0
 * @link       
 * @license    http://www.sdo.com
 */

include_once(dirname(__FILE__).'/../config/UCConfFace.php');

class UCLibFace
{

	private $_uid;
	private $_error_no;

	/**
	 * 构造函数
	 * @param int $uid 用户id
	 */
	public function __construct($uid)
	{
		$this->_uid = $uid;
	}
	
	/**
	 * 创建用户头像路径
	 */
	public function createFacePrefix()
	{
		$str = md5($this->_uid);
		return '/' . substr($str, 0, 2) . '/' . substr($str, 2, 2) . '/' . $this->_uid;
	}
	
	/**
	 * 创建用户头像路径
	 * @param	string	$srcFile	路径源地址
	 * @param	string	$desFile	路径目的地址
	 */
	public function sendfile($srcFile, $desFile)
	{
		$sock = null;
		$server = $this->_getServer($this->_uid);
		if(!($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)))
		{
			$this->_error_no = self::FACE_ERROR_SCOKET_CREATE;
			return false;
		}
		if(!socket_connect($sock, $server['server'],$server['port'])) 
		{
			$this->_error_no = self::FACE_ERROR_SCOKET_CONNECT;
			return false;
		}
		socket_write($sock, "save\n{$desFile}\n" . filesize($srcFile) . "\n");
		socket_write($sock, file_get_contents($srcFile));
		socket_close($sock);
		unset($sock);
		
		if(!($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)))
		{
			$this->_error_no = self::FACE_ERROR_SCOKET_CREATE;
			return false;
		}
		if(!socket_connect($sock, $server['backup'],$server['port'])) 
		{
			$this->_error_no = self::FACE_ERROR_SCOKET_CONNECT;
			return false;
		}
		socket_write($sock, "save\n{$desFile}\n" . filesize($srcFile) . "\n");
		socket_write($sock, file_get_contents($srcFile));
		socket_close($sock);
		unset($sock);
	}
	
	/**
	 * 获取头像服务器地址
	 */
	private function _getServer()
	{
		$key = hexdec(substr(md5($this->_uid), 0, 2));
		if($key<=hexdec('3f'))
		{
			$value = 0;
			$backup = 1;
		}
		else if($key<=hexdec('7f'))
		{
			$value = 1;
			$backup = 0;
		}
		else if($key<=hexdec('bf'))
		{
			$value = 2;
			$backup = 3;
		}
		else if($key<=hexdec('ff'))
		{
			$value = 3;
			$backup = 2;
		}
		$ar_server = UCConfFace::getServer();
		return array('port'=>$ar_server['port'],'server'=>$ar_server['server'][$value],'backup'=>$ar_server['server'][$backup]);
	}
}

?>